<template>
    <div class="system-index">
        <el-card class="page-card">
            <div class="page-header">
                <h2>系统管理</h2>
                <el-button type="success" @click="showAddDialog" icon="Plus">新增管理员</el-button>
            </div>

            <!-- 查询表单 -->
            <el-form :model="admin" ref="formRef" label-width="120px" label-position="right" class="search-form" >
                <el-row :gutter="20">
                    <el-col :span="10">
                        <el-form-item label="管理员名称" prop="name">
                            <el-input v-model="admin.name" placeholder="请输入管理员名称" clearable/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="10">
                        <el-form-item label="真实姓名" prop="realname">
                            <el-input v-model="admin.realname" placeholder="请输入真实姓名" clearable/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4" class="search-buttons">
                        <el-space>
                            <el-button type="primary" @click="doList" icon="Search">查询</el-button>
                            <el-button type="default" @click="resetForm()" icon="Refresh">重置</el-button>
                        </el-space>
                    </el-col>
                </el-row>
            </el-form>

            <!-- 数据表格 -->
            <el-table :data="tableData" stripe hover-row border style="width: 100%" class="data-table" >
                <el-table-column type="index" label="序号" width="80" align="center"/>
<!--                <el-table-column prop="id" label="ID" align="center"/>-->
                <el-table-column prop="name" label="管理员名称" align="center"/>
                <el-table-column prop="realname" label="真实姓名" align="center"/>
                <el-table-column label="操作" width="240" align="center">
                    <template #default="scope">
                        <el-space size="small">
                            <el-button type="primary" size="small" @click="showDetailPage(scope.row)" icon="View">详情</el-button>
                            <el-button type="warning" size="small" @click="showUpdateDialog(scope.row)" icon="Edit">更新</el-button>
                            <el-button type="danger" size="small" @click="doDelete(scope.row.id)" icon="Delete">删除</el-button>
                        </el-space>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页控件 -->
            <div class="pagination">
                <el-pagination
                    style="float: left;"
                    layout="total, sizes, prev, pager, next, jumper"
                    :page-sizes="[5, 10, 20, 50]"
                    v-model:current-page="page.pageNum"
                    v-model:page-size="page.pageSize"
                    :total="page.total"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                />
            </div>

        </el-card>

        <!-- 新增对话框 -->
        <el-dialog v-model="addDialogVisible" title="新增管理员" width="50%" top="10vh" destroy-on-close>
            <add-page @flushPage="doFlushPage" @closeDialog="addDialogVisible = false"/>
        </el-dialog>

        <!-- 更新对话框 -->
        <el-dialog v-model="updateDialogVisible" title="更新管理员" width="50%" top="10vh" destroy-on-close>
            <update-page ref="updatePageRef" @flushPage="doFlushPage" @closeDialog="updateDialogVisible = false"/>
        </el-dialog>

        <!-- 详情页面 -->
        <detail-page ref="detailPageRef"/>
    </div>
</template>

<style scoped>
.system-index {
    padding: 20px;
}

.page-card {
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    border-radius: 8px;
    overflow: hidden;
}

.page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px;
    border-bottom: 1px solid #f0f0f0;
    margin-bottom: 20px;
}

.page-header h2 {
    margin: 0;
    font-size: 20px;
    color: #303133;
}

.search-form {
    padding: 0 20px 20px;
}

.search-buttons {
    display: flex;
    align-items: center;
    margin-top: -18px;
}

.data-table {
    margin: 0 20px 20px;
}

.pagination {
    margin: 20px;
    padding: 10px 0;
    background: white;
    border-top: 1px solid #ebeef5;
    position: relative; /* 改为相对定位 */
    z-index: 1; /* 确保不被遮挡 */
}
</style>

<script setup lang="ts">
import {ref, onMounted, nextTick} from 'vue'
import {ElMessage, FormInstance} from "element-plus";
import axios from 'axios'
import DetailPage from './DetailPage.vue';
import AddPage from './AddPage.vue';
import UpdatePage from './UpdatePage.vue';

//------------------------- 重置按钮 -----------------------------
const formRef = ref<FormInstance>();
const resetForm = () => {
    formRef.value?.resetFields()
}

//------------------------- form 表单 -----------------------------
const admin = ref({
    id: '',
    name: '',
    realname: ''
});

// -------------------------- table 表格 ----------------------------
const tableData = ref([]);

// 分页信息
const page = ref({
    pageNum: 1,     // 当前页码
    pageSize: 5,   // 每页显示的记录数
    pages: 0,       // 总页数
    total: 0        // 总记录数
})

// 处理分页大小变化
const handleSizeChange = (val: number) => {
    page.value.pageSize = val;
    page.value.pageNum = 1; // 重置到第一页
    doList();
};

// 处理页码变化
const handleCurrentChange = (val: number) => {
    page.value.pageNum = val;
    doList();
};

// 分页重置
const doPageReset = () => {
    page.value.pageNum = 1;
    page.value.pageSize = 5;
    page.value.pages = 0;
    page.value.total = 0;
}

// 查询
const doList = async () => {
    try {
        const params = {
            ...admin.value,
            pageNum: page.value.pageNum,
            pageSize: page.value.pageSize
        };

        const { data } = await axios.get('/api/admin/list', { params });
        console.log('API响应数据:', data);

        // 确保处理正确的分页数据结构
        if (data && data.data) {
            // 标准分页响应结构 { data: { list: [], total: 100 } }
            tableData.value = data.data.list || [];
            page.value.total = data.data.total || 0;
        } else if (data && data.list) {
            // 兼容结构 { list: [], total: 100 }
            tableData.value = data.list;
            page.value.total = data.total || 0;
        } else {
            // 其他结构处理
            tableData.value = Array.isArray(data) ? data : [];
            page.value.total = tableData.value.length;
        }

        console.log('表格数据:', tableData.value);
        console.log('分页信息:', page.value);
    } catch (error) {
        console.error('查询失败:', error);
        ElMessage.error('获取数据失败');
    }
}
// 删除
const doDelete = async (id)=>{
    const {data} = await axios.delete('/api/admin/'+id);
    if(data > 0){
        doFlushPage();		// 删除成功，刷新表格数据
        ElMessage.success('删除成功');
    }else{
        ElMessage.error('删除失败');
    }
}

// 刷新页面：表单重置、分页重置、重新查询
const doFlushPage = () => {
    resetForm();
    doPageReset();
    doList();
}

// 初始化
onMounted(()=>{
    doList();   // 查询数据
})

//--------------------------- 新增 对话框 ---------------------------
const addDialogVisible = ref(false);
const showAddDialog = ()=>{
    addDialogVisible.value = true;
}

//--------------------------- 更新 对话框 ---------------------------
const updateDialogVisible = ref(false);
const updatePageRef = ref(); // 组件引用
const showUpdateDialog = (obj)=>{
    updateDialogVisible.value = true;
    nextTick(()=>{
        updatePageRef.value.handleUpdateData(obj);
    })
}

//--------------------------- 详显 页面---------------------------
// 详显组件引用
const detailPageRef = ref();
const showDetailPage = (obj)=>{
    detailPageRef.value.handleDetailData(obj);
}
</script>
<style scoped>
</style>